#!/bin/bash

set -e
pushd $(cd $(dirname ${0})/..; pwd) > /dev/null

case "${OSTYPE}" in
    msys*) python="winpty python";;
    *) python="python3";;
esac

clean() {
    echo "om clean"
    rm -rf "./third_party/source/ascend"
}

sync() {
    echo "om sync"
    mkdir -p "./third_party/source/ascend/metadef/proto"
    curl --silent --location --output "./third_party/source/ascend/metadef/proto/ge_ir.proto" "https://gitee.com/ascend/metadef/raw/master/proto/ge_ir.proto?raw=true"
}

schema() {
    echo "om schema"
    [[ $(grep -U $'\x0D' ./source/om-proto.js) ]] && crlf=1
    node ./tools/protoc.js --text --root om --out ./source/om-proto.js ./third_party/source/ascend/metadef/proto/ge_ir.proto
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/om-proto.js ./source/om-proto.js
    fi
}

metadata() {
    echo "om metadata"
    [[ $(grep -U $'\x0D' ./source/om-metadata.json) ]] && crlf=1
    venv
    export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
    ${python} ./tools/om-script.py metadata
    deactivate
    if [[ -n ${crlf} ]]; then
        unix2dos --quiet --newfile ./source/om-metadata.json ./source/om-metadata.json
    fi
}

while [ "$#" != 0 ]; do
    command="$1" && shift
    case "${command}" in
        "clean") clean;;
        "sync") sync;;
        "schema") schema;;
        "metadata") metadata;;
    esac
done
